#include <stdio.h>
#include <stdlib.h>
#include <fcntl.h>
#include <unistd.h>
#include <sys/ioctl.h>
#include <sys/mman.h>
#include <linux/fb.h>

int main() {
    // 打开帧缓冲设备
    int fb_fd = open("/dev/fb0", O_RDWR);
    if (fb_fd == -1) {
        perror("无法打开帧缓冲设备");
        return 1;
    }

    // 获取屏幕可变信息
    struct fb_var_screeninfo var_info;
    if (ioctl(fb_fd, FBIOGET_VSCREENINFO, &var_info)) {
        perror("无法获取屏幕信息");
        close(fb_fd);
        return 1;
    }

    // 获取屏幕固定信息
    struct fb_fix_screeninfo fix_info;
    if (ioctl(fb_fd, FBIOGET_FSCREENINFO, &fix_info)) {
        perror("无法获取固定信息");
        close(fb_fd);
        return 1;
    }

    // 校验分辨率
    if (var_info.xres != 800 || var_info.yres != 480) {
        fprintf(stderr, "不支持的屏幕分辨率\n");
        close(fb_fd);
        return 1;
    }

    // 计算颜色值（ARGB8888格式）
    unsigned int red_value = 0xFF << var_info.red.offset |
                             0x00 << var_info.green.offset |
                             0x00 << var_info.blue.offset;

    // 映射帧缓冲内存
    unsigned int *fb_ptr = mmap(NULL, 
                               fix_info.smem_len,
                               PROT_READ | PROT_WRITE,
                               MAP_SHARED,
                               fb_fd,
                               0);
    
    if (fb_ptr == MAP_FAILED) {
        perror("内存映射失败");
        close(fb_fd);
        return 1;
    }

    // 填充颜色数据
    for (int y = 0; y < var_info.yres; y++) {
        for (int x = 0; x < var_info.xres; x++) {
            // 计算内存偏移量（考虑行填充）
            unsigned int *pixel = fb_ptr + 
                                 (y * fix_info.line_length / sizeof(unsigned int)) + 
                                 x;
            *pixel = red_value;
        }
    }

    // 清理资源
    munmap(fb_ptr, fix_info.smem_len);
    close(fb_fd);
    return 0;
}